package me.sealer.interview;

import java.util.Stack;

/**
 * @author sealer
 * @date 2018/06/19.
 * @email 1178884049@qq.com
 */
public class ReverseString {

    public static void main(String[] args) {
        String s = "a bc def   g  ";
        String result = reverseStr(s);
        System.out.println(result);
    }

    /**
     * 将s字符串翻转
     * 所有单词保留正序
     * 单词之间顺序翻转
     * 保留空格及其个数
     * 空格之间顺序翻转
     *
     * @param s
     * @return
     */
    public static String reverseStr(String s) {
        Stack<String> stack = new Stack<>();
        int len = s.length();
        int i = 0;
        while (i < len) {
            if (' ' == s.charAt(i)) {
                stack.push(s.charAt(i) + "");
                i++;
            } else {
                StringBuilder sb = new StringBuilder();
                while (i < len && !(' ' == s.charAt(i))) {
                    sb.append(s.charAt(i));
                    i++;
                }
                stack.push(sb.toString());
            }
        }

        StringBuilder sbRet = new StringBuilder();
        while (!stack.isEmpty()) {
            sbRet.append(stack.pop());
        }

        return sbRet.toString();
    }
}
